import { SvgIcon } from '@/components/icon';
import useWindowWidth from '@/hooks/event/use-window-width';
import { Alert, Drawer, Spin } from 'antd';
import React, { memo, useEffect, useRef, useState } from 'react';
import './file-viewer.scss';
import { log } from 'console';
import { CircleLoading } from '@/components/loading';
import { url } from 'inspector';
import Markdown from '@/components/markdown';
import { addTableHeader } from '@/utils/common';

interface Props {
  previewUrl: string;
  loading: boolean;
  setLoading: (loading: boolean) => void;
  fileName?: string;
}

const FilePreviewer = ({ previewUrl, loading, setLoading, fileName = '' }: Props) => {
  const [isIframeError, setIsIframeError] = useState(false);
  const [fileContent, setFileContent] = useState<string>('');
  const [isMd, setIsMd] = useState(true);

  const readFile = async (url: string) => {
    const response = await fetch(url);
    if (response.ok) {
      const text = await response.text();
      setFileContent(text);
    } else {
      setIsIframeError(true);
    }
  };

  const onIframeError = () => {
    setIsIframeError(true);
  };

  const onIframeLoad = (event: React.SyntheticEvent<HTMLIFrameElement, Event>) => {
    const iframe = event.target;
    try {
      const doc = iframe?.contentDocument || iframe.contentWindow?.document;
      if (!doc.body.innerHTML || doc.body.innerHTML.includes('500 Internal Server Error')) {
        console.error('Server returned a 500 error');
        setIsIframeError(true);
      } else {
        const style = iframe.contentDocument.createElement('style');
        style.textContent = `
          /* 纵向滚动条 */
         ::-webkit-scrollbar {
            width: 8px;
            height: 8px;
            background-color: #f5f5f5;
          }
          ::-webkit-scrollbar-track {
            -webkit-box-shadow: inset 0 0 6px rgba (0, 0, 0, 0.3);
            border-radius: 10px;
            background-color: #f5f5f5;
          }
          ::-webkit-scrollbar-thumb {
            cursor: pointer;
            border-radius: 10px;
            -webkit-box-shadow: inset 0 0 6px rgba (0, 0, 0, 0.3);
            background-color: #bbbbbb;
          }
        `;
        iframe.contentDocument.head.appendChild(style);
      }
    } catch (e) {
      console.error(e);
      setIsIframeError(true);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    setIsIframeError(false);
    setLoading(true);
    if (fileName.endsWith('.md')) {
      setIsMd(true);
      readFile(previewUrl);
    } else {
      setIsMd(false);
    }
  }, [fileName, previewUrl]);

  return (
    <div className="relative h-full w-full">
      {previewUrl && (
        <React.Fragment>
          {!isIframeError && !isMd && !fileName.endsWith('.md') && (
            <iframe
              key={previewUrl}
              src={previewUrl}
              style={{ width: '100%', height: '100%', border: 'none' }}
              onLoad={onIframeLoad}
              onError={onIframeError}
            />
          )}

          {isMd && (
            <div className="h-full overflow-y-auto rounded-lg bg-[#FFF] p-6">
              <Markdown source={addTableHeader(fileContent)} />
            </div>
          )}

          {(loading || isIframeError) && !isMd && previewUrl && (
            <div className="pointer-events-none absolute left-0 top-0 h-full w-full">
              <span>{loading ? <CircleLoading /> : '加载失败'}</span>
            </div>
          )}
        </React.Fragment>
      )}
      {!previewUrl && (
        <div className="pointer-events-none absolute left-0 top-0 flex h-full w-full items-center justify-center text-center">
          文件不可用或可能已被删除
        </div>
      )}
    </div>
  );
};

export default memo(FilePreviewer);
